import json
import os
from flask import Flask,jsonify,render_template, request, send_from_directory, make_response, session
# import userBackend as uB
from code.data.User import User
from code.data.Notice import Notice
from code.data.File import File
from code.backend.user_backend import UserBackend
from code.backend.notice_backend import NoticeBackend
from code.backend.file_backend import FileBackend
from wsgiref.simple_server import make_server
from code.data.Homework import Homework
from code.backend.homework_backend import HomeworkBackend
from code.data.Answer import Answer
from code.backend.answer_backend import AnswerBackend

app = Flask(__name__)   # code: course management system
class Config(object):
    SECRET_KEY = "DJFAJLAJAFKLJQ"
app.config.from_object(Config())

@app.route('/')
def login():
  return render_template('login.html')

@app.route('/user_index')
def user_index():
  return render_template('index.html',
                         usertype=session.get("usertype"),
                         username=session.get("username"),
                         userid=session.get("userid"),
                         useremail=session.get("useremail"))

@app.route('/announce_manage')
def html_announce_manage():
  return render_template('announce_manage.html')

@app.route('/update_notice_manage', methods=["POST"])
def update_notice_manage():
    data = request.get_json()
    user = User(userID=data["userID"])
    result = NoticeBackend.notice_display()
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", noticelist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", noticelist=[])}

@app.route('/delete_notice', methods=["POST"])
def delete_notice():
    data = request.get_json()
    print(data)
    user = User(userID=data["userid"])
    noticeid = data["noticeid"]
    notice = Notice(noticeID=int(noticeid), userID=data["userid"])
    result = NoticeBackend.notice_delete(user, notice)
    print(result)
    return str(result)
@app.route('/add_user')
def add_user():
  return render_template('add_user.html')

@app.route('/act_delete_user', methods=["POST"])
def user_delete():
    data = request.get_json()
    user = User(userID=data["userid"])
    result = UserBackend.delete_user_(user)
    if isinstance(result, int):
        return str(result)
    return "1"

@app.route('/accept_register', methods=["POST"])
def accept_register():
    data = request.get_json()
    user = User(userID=data["userid"])
    result = UserBackend.active_user(user)
    print(result)
    if isinstance(result, int):
        return str(result)
    return "1"

@app.route('/reject_register', methods=["POST"])
def reject_register():
    data = request.get_json()
    user = User(userID=data["userid"])
    result = UserBackend.delete_user_(user)
    if isinstance(result, int):
        return str(result)
    return "1"

@app.route('/update_user_request', methods=["POST"])
def update_user_request():
    data = request.get_json()
    result = UserBackend.all_register_request()
    print(result)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", userlist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", userlist=[])}

@app.route('/update_user_manage', methods=["POST"])
def update_user_manage():
    data = request.get_json()
    result = UserBackend.all_user()
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", userlist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", userlist=[])}

@app.route('/file_manage')
def file_manage():
  return render_template('file_manage.html', filelist=[])

@app.route('/update_file_manage', methods=["POST"])
def update_file_manage():
    data = request.get_json()
    user = User(userID=data["userID"])
    result = FileBackend.file_init_display(user)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", filelist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", filelist=[])}

@app.route('/delete_file', methods=["POST"])
def delete_file():
    data = request.get_json()
    print(data)
    user = User(userID=data["userid"])
    for fileid in data["fileids"]:
        file = File(fileID=int(fileid), userID=data["userid"])
        result = FileBackend.file_delete(user, file)
        if result != 1:
            break
        # os.remove("")
    print(result)
    return str(result)

@app.route('/act_download_file', methods=["POST"])
def act_download_file():
    data = request.get_json()
    print(data)
    user = User(userID=data["userid"])
    file = File(fileID=int(data["fileid"]), userID=data["userid"])
    result = FileBackend.file_download(user, file)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    print(os.path.split(result.path)[0],result.filename)
    return send_from_directory(os.path.split(result.path)[0], result.filename, as_attachment=True)

@app.route('/download_file')
def download_file():
  return render_template('download_file.html')

@app.route('/comments')
def comments():
  return render_template('comments.html')

@app.route('/delete_user')
def delete_user():
  return render_template('delete_user.html')

@app.route('/homework_teacher')
def homework_teacher():
  return render_template('homework_teacher.html')

@app.route('/update_homework_manage', methods=["POST"])
def update_homework_manage():
    data = request.get_json()
    user = User(userID=data["userID"])
    result = HomeworkBackend.homework_init_display_for_teacher(user)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", homeworklist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", homeworklist=[])}

@app.route('/delete_homework', methods=["POST"])
def delete_homework():
    data = request.get_json()
    print(data)
    user = User(userID=data["userid"])
    homeworkid = data["homeworkid"]
    homework = Homework(homeworkID=int(homeworkid))
    result = HomeworkBackend.homework_delete(user, homework)
    print(result)
    return str(result)

@app.route('/homework_student')
def homework_student():
  return render_template('homework_student.html')

@app.route('/update_homework_commit', methods=["POST"])
def update_homework_commit():
    data = request.get_json()
    user = User(userID=data["userID"])
    result = HomeworkBackend.homework_init_display_for_student(user)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", homeworklist=result)}
    return {"resultcode": "1", "html": render_template(data["html"]+".html", homeworklist=[])}

@app.route('/update_homework')
def update_homework():
  return render_template('update_homework.html')

@app.route('/homework_checklist')
def homework_checklist():
    data = request.get_json()
    user = User(userID=data["userID"])
    answer = Answer(homeworkID=data["homeworkID"])
    result = AnswerBackend.init_display_one_homework_all_answer_for_teacher(user, answer)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"] + ".html", checklist=result)}
    return {"resultcode": "1", "html": render_template('homework_checklist.html', )}

@app.route('/update_homework_checklist', methods=["POST"])
def update_homework_checklist():
    data = request.get_json()
    user = User(userID=data["userID"])
    answer = Answer(homeworkID=data["homeworkID"])
    result = AnswerBackend.init_display_one_homework_all_answer_for_teacher(user, answer)
    if isinstance(result, int):
        return {"resultcode": str(result)}
    elif result:
        return {"resultcode": "1", "html": render_template(data["html"]+".html", checklist=result)}
    return {"resultcode": "1", "html": render_template(data["html"] + ".html", checklist=[])}

@app.route('/announce_explore')
def announce_explore():
  return render_template('announce_explore.html')

@app.route("/login", methods=['POST'])
def act_login():
    data = request.get_json()
    info = UserBackend.login(data["userID"], data["userpassword"])
    if isinstance(info,int):
        return jsonify({
            "resultCode": str(info),
        })
    else:
        session["usertype"] = info.type
        session["userid"] = info.userID
        session["username"] = info.name
        session["useremail"] = info.email
        return jsonify({
            "resultCode": '1',
            "userID": info.userID,
            "username": info.name
        })

@app.route("/register")
def register():
    return render_template('register.html')

@app.route("/act_register", methods=['POST'])
def act_register():
    data = request.get_json()
    print(data["userID"])
    user = User(userID=data["userID"],
                password=data["userpassword"],
                name=data["username"],
                email=data["useremail"]
                )
    errorID = UserBackend.register(user)
    print(errorID)
    return str(errorID)

@app.route("/act_announce_manage")
def announce_manage():
    data = request.get_json()
    user = User(userID=data["userID"])
    notice = Notice(content=data["announce_content"],
                type=data["announce_type"]
                )
    errorID = NoticeBackend.notice_announce(user, notice)
    return errorID

@app.route("/new_announce")
def new_announce():
    return render_template('new_announce.html')

@app.route("/new_homework")
def new_homework():
    return render_template('new_homework.html')

@app.route("/act_new_homework", methods=['POST'])
def act_new_homework():
    userid = request.form["userID"]
    homework_question = request.form["homework_question"]
    with_file = request.form["with_file"]
    if with_file == "yes":
        file = request.files['file']
        filename = file.filename
        filepath = "fileDB/"+filename
        file.save(filepath)
        homework = Homework(content=homework_question, file_path=filepath,
                            file_size=os.path.getsize(filepath), userID=userid)
    else:
        homework = Homework(content=homework_question, userID=userid)
    user = User(userID=userid)
    result = HomeworkBackend.homework_announce(user, homework)
    print(result)
    return str(result)

@app.route("/homework_commmit")
def homework_commit():
    return render_template('homework_commit.html')

@app.route("/announcement", methods=['POST'])
def announcement():
    data = request.get_json()
    user = User(userID=data["userID"])
    notice = Notice(userID=data["userID"],
                content=data["announce_content"],
                type=data["announce_type"]
                )
    errorID = NoticeBackend.notice_announce(user, notice)
    print(errorID)
    return str(errorID)

@app.route("/uploadfile", methods=['POST'])
def uploadfile():
    userid = request.form["userID"]
    file = request.files['file']
    filename = file.filename
    filepath = "fileDB/"+filename
    file.save(filepath)
    user = User(userID=userid)
    _file = File(filename=file.filename, path=filepath, size=os.path.getsize(filepath), userID=userid)
    result = FileBackend.file_upload(user, _file)
    return str(result)

if __name__ == '__main__':
    server = make_server('0.0.0.0', 5000, app)
    server.serve_forever()
    app.run()


